﻿using System;

namespace Sencha.Serialization.Bson.Serializers
{
	public class BsonRegexSerializer : TypeSerializer<BsonRegex>
	{
		public override BsonRegex Deserialize(IJsonReader reader)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");

			if (reader is IBsonReader)
				return this.DeserializeBson(reader as IBsonReader);

			// http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON
			// { "$regex" : "<sRegex>", "$options" : "<sOptions>" }

			reader.ReadObjectBegin();
			var pattern = reader.ReadMember<string>("$regex");
			var options = reader.ReadMember<string>("$options");
			reader.ReadObjectEnd(false);

			return new BsonRegex(pattern, options);
		}
		private BsonRegex DeserializeBson(IBsonReader reader)
		{			
			if (reader.Token != BsonToken.Regex)
				throw new Exceptions.UnexpectedBsonToken(reader, reader.Token, BsonToken.Regex);

			var regex = (BsonRegex)reader.RawValue;
			return regex;
		}
		public override void Serialize(IJsonWriter writer, BsonRegex value)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");

			if (value == null)
			{
				writer.WriteNull();
				return;
			}

			if (writer is IBsonWriter)
			{
				this.SerializeBson(writer as IBsonWriter, value);
				return;
			}

			// http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON
			// { "$regex" : "<sRegex>", "$options" : "<sOptions>" }

			writer.WriteObjectBegin();
			writer.WriteMember("$regex", value.Pattern);
			writer.WriteMember("$options", value.Options);
			writer.WriteObjectEnd();
		}
		private void SerializeBson(IBsonWriter writer, BsonRegex value)
		{		
			writer.Write(BsonToken.Regex, value);
		}
	}
}
